<template>
  <div class="purchase-order-detail">
    <div class="header">
      <h2>进货单详情</h2>
      <el-button @click="$router.back()">返回</el-button>
    </div>

    <el-descriptions v-if="order" :column="2" border>
      <el-descriptions-item label="订单号">{{ order.order_number }}</el-descriptions-item>
      <el-descriptions-item label="经销商">{{ order.dealer_name }}</el-descriptions-item>
      <el-descriptions-item label="下单日期">{{ formatDate(order.order_date) }}</el-descriptions-item>
      <el-descriptions-item label="订单状态">
        <el-tag :type="getStatusType(order.status)">
          {{ getStatusText(order.status) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="备注" :span="2">{{ order.notes || '无' }}</el-descriptions-item>
    </el-descriptions>

    <div class="items-list" v-if="order">
      <h3>商品列表</h3>
      <el-table :data="order.items" border style="width: 100%">
        <el-table-column prop="item_name" label="商品名称" />
        <el-table-column prop="item_type" label="类型">
          <template #default="{ row }">
            {{ row.item_type === 'book' ? '图书' : '商品' }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import PurchaseOrderService from '@/api/purchaseOrderService'

const route = useRoute()
const router = useRouter()
const order = ref(null)

async function fetchOrderDetails() {
  try {
    const response = await PurchaseOrderService.getOrderById(route.params.id)
    order.value = response.data
  } catch (error) {
    console.error('Error fetching order details:', error)
    ElMessage.error('获取订单详情失败')
    router.push('/purchase-orders')
  }
}

function getStatusType(status) {
  const types = {
    pending: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

function getStatusText(status) {
  const texts = {
    pending: '待处理',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

function formatDate(date) {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  fetchOrderDetails()
})
</script>

<style scoped>
.purchase-order-detail {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.items-list {
  margin-top: 20px;
}

.items-list h3 {
  margin-bottom: 15px;
}
</style> 